package com.tyut.planeGame.controller;

import com.tyut.planeGame.entity.dto.TopUser;
import com.tyut.planeGame.entity.form.LoginForm;
import com.tyut.planeGame.entity.form.RegisterForm;
import com.tyut.planeGame.entity.form.UpdateForm;
import com.tyut.planeGame.service.UserService;
import com.tyut.planeGame.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("User")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册
     */
    @PostMapping("/register")
    public R register(@RequestBody RegisterForm registerForm) {
        try {
            userService.register(registerForm);
            return R.ok("注册成功");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 登陆
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginForm loginForm) {
        try {
            String token = userService.login(loginForm);
            return R.ok().put("token", token);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 返回密保问题
     */
    @GetMapping("/GetQuestion")
    public R GetQuestion(@RequestParam String username) {
        try {
            String question = userService.GetQuestion(username);
            return R.ok().put("question", question);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/UpdatePassword")
    public R UpdatePassword(@RequestBody UpdateForm updateForm) {
        try {
            userService.UpdatePassword(updateForm);
            return R.ok("修改成功");
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 保存最高分
     */
    @GetMapping("/SaveScore")
    public R SaveScore(@RequestParam int score) {
        try {
            int TopScore = userService.SaveScore(score);
            return R.ok().put("TopScore", TopScore);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 获取最高分
     */
    @GetMapping("/GetScore")
    public R GetScore() {
        try {
            int score = userService.GetScore();
            return R.ok().put("score", score);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 获取排行榜
     */
    @GetMapping("/GetTopUser")
    public R GetTop() {
        try {
            List<TopUser> topUserList = userService.getTopUserList();
            return R.ok().put("TopUserList", topUserList);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }
}
